<template>
  <div class="shopping-cart">
    <h2>购物车</h2>
    <div v-if="cartItems.length === 0" class="empty-cart">
      购物车是空的，去 <router-link to="/">购物</router-link>
    </div>
    
    <div v-else>
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <el-image :src="item.product.imageUrl" :alt="item.product.name" class="product-image" />
        <div class="item-info">
          <h3>{{ item.product.name }}</h3>
          <p class="price">¥{{ item.product.price }}</p>
        </div>
        <div class="quantity-control">
          <el-input-number 
            v-model="item.quantity" 
            :min="1" 
            :max="item.product.stock"
            @change="updateQuantity(item)"
          />
        </div>
        <el-button type="danger" @click="removeItem(item.id)">删除</el-button>
      </div>
      
      <div class="cart-summary">
        <div class="total">
          总计: <span class="total-price">¥{{ totalAmount }}</span>
        </div>
        <el-button type="primary" @click="checkout">结算</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const store = useStore()
const router = useRouter()
const cartItems = ref([])

const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.product.price * item.quantity
  }, 0)
})

const loadCartItems = async () => {
  try {
    const response = await store.dispatch('cart/getCartItems')
    cartItems.value = response
  } catch (error) {
    ElMessage.error('加载购物车失败')
  }
}

const updateQuantity = async (item) => {
  try {
    await store.dispatch('cart/updateCartItem', {
      id: item.id,
      quantity: item.quantity
    })
  } catch (error) {
    ElMessage.error('更新数量失败')
  }
}

const removeItem = async (itemId) => {
  try {
    await store.dispatch('cart/removeCartItem', itemId)
    await loadCartItems()
    ElMessage.success('商品已移除')
  } catch (error) {
    ElMessage.error('移除商品失败')
  }
}

const checkout = () => {
  router.push('/checkout')
}

onMounted(() => {
  loadCartItems()
})
</script>

<style scoped>
.shopping-cart {
  padding: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 20px;
}

.item-info {
  flex: 1;
}

.quantity-control {
  margin: 0 20px;
}

.cart-summary {
  margin-top: 20px;
  text-align: right;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}
</style> 